package cn.congine.wizarpos.mall.action;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import cn.congine.wizarpos.mall.common.RespMessage;
import cn.congine.wizarpos.mall.entity.MrtMerchantCarousel;
import cn.congine.wizarpos.mall.model.ErpProduct;
import cn.congine.wizarpos.mall.model.open.AccessTokenInput;
import cn.congine.wizarpos.mall.model.open.CanyinSalesOrderSubmitInput;
import cn.congine.wizarpos.mall.model.open.CanyinSalesOrderSubmitOutput;
import cn.congine.wizarpos.mall.model.open.Category;
import cn.congine.wizarpos.mall.model.open.CateringDetail;
import cn.congine.wizarpos.mall.model.open.CateringOrderQueryInput;
import cn.congine.wizarpos.mall.model.open.CateringOrderQueryOutput;
import cn.congine.wizarpos.mall.model.open.CateringSaleOrderBindingInput;
import cn.congine.wizarpos.mall.model.open.CateringSaleOrderBindingOutput;
import cn.congine.wizarpos.mall.model.open.CateringSaleOrderDto;
import cn.congine.wizarpos.mall.model.open.CateringSaleOrderListQueryInput;
import cn.congine.wizarpos.mall.model.open.CateringSaleOrderListQueryOutput;
import cn.congine.wizarpos.mall.model.open.CateringSaleOrderQueryInput;
import cn.congine.wizarpos.mall.model.open.CateringSaleOrderQueryOutput;
import cn.congine.wizarpos.mall.model.open.CateringSaleOrderQueryV1_1Output;
import cn.congine.wizarpos.mall.model.open.CateringTableDetailOutput;
import cn.congine.wizarpos.mall.model.open.CateringTableDetailV1_1Input;
import cn.congine.wizarpos.mall.model.open.CommonResultOutput;
import cn.congine.wizarpos.mall.model.open.GetShopInfoInput;
import cn.congine.wizarpos.mall.model.open.GetShopInfoOutput;
import cn.congine.wizarpos.mall.model.open.GetTabelIdInput;
import cn.congine.wizarpos.mall.model.open.GetTabelIdOutput;
import cn.congine.wizarpos.mall.model.open.Merchandise;
import cn.congine.wizarpos.mall.model.open.MerchandiseSyncInput;
import cn.congine.wizarpos.mall.model.open.MerchandiseSyncOutput;
import cn.congine.wizarpos.mall.model.open.MerchantDef;
import cn.congine.wizarpos.mall.model.open.MerchantDefQueryInput;
import cn.congine.wizarpos.mall.model.open.MerchantDefQueryOutput;
import cn.congine.wizarpos.mall.model.open.OrderDetail;
import cn.congine.wizarpos.mall.model.open.OrderDetailV1_1;
import cn.congine.wizarpos.mall.model.open.Payment;
import cn.congine.wizarpos.mall.model.open.ProductCategorySyncInput;
import cn.congine.wizarpos.mall.model.open.ProductCategorySyncOutput;
import cn.congine.wizarpos.mall.model.open.SaleOrder;
import cn.congine.wizarpos.mall.model.open.ShopInfoPair;
import cn.congine.wizarpos.mall.model.open.TableOrder;
import cn.congine.wizarpos.mall.model.open.TicketInfoPayUse;
import cn.congine.wizarpos.mall.model.open.WeChartMemberInfoQueryInput;
import cn.congine.wizarpos.mall.model.open.WeChartMemberInfoQueryOutput;
import cn.congine.wizarpos.mall.model.open.WxSaleOrderQueryInput;
import cn.congine.wizarpos.mall.model.open.WxSaleOrderQueryV1_1Output;
import cn.congine.wizarpos.mall.service.MrtMerchantCarouselService;
import cn.congine.wizarpos.mall.service.impl.WPosHttpClient;
import cn.congine.wizarpos.mall.service.impl.WizarposOpenRestClient;
import cn.congine.wizarpos.mall.tenpay.util.MD5Util;
import cn.congine.wizarpos.mall.utils.Function;
import cn.congine.wizarpos.mall.utils.SysConstants;
import cn.congine.wizarpos.mall.utils.Utils;
import cn.congine.wizarpos.mall.utils.WxSignUtil;
import cn.congine.wizarpos.mall.vo.CateringReOrderView;
import cn.congine.wizarpos.mall.vo.ProductView;

@Controller
@RequestMapping(value = "/dgd")
public class CanyinAction {
	private Logger logger = Logger.getLogger(CanyinAction.class);

	@Autowired
	private WPosHttpClient wPosHttpClient;
	@Autowired
	private WizarposOpenRestClient wizarposOpenRestClient;
	 
	@Resource(name = "messageSource")
	private MessageSource messageSource;
	
	@Autowired
	private MrtMerchantCarouselService mrtMerchantCarouselService;
	/**
	 * 点单详情
	 * 
	 * @param mid
	 * @param orderId
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "/order_detail")
	public ModelAndView orderDetail(
			@RequestParam(value = "orderId", required = true) String orderId,
			@RequestParam(value = "mid", required = true) String mid,
			HttpServletRequest httpRequest) {
		String openId = (String) httpRequest.getSession().getAttribute("openId");
		String cardId = (String) httpRequest.getSession().getAttribute("mrtCardId");
		if (StringUtils.isEmpty(openId) || StringUtils.isEmpty(cardId)) {//session过期，跳转到登录注册页面
			return new ModelAndView("forward:/vip/login");
		}
		int productsNum = 0;
		
		CateringSaleOrderQueryInput input = new CateringSaleOrderQueryInput();
		input.setMid(mid);
		input.setOrderId(orderId);
		CateringSaleOrderQueryV1_1Output output = (CateringSaleOrderQueryV1_1Output) wizarposOpenRestClient.postV1_1(input, "/canyin/saleorder/query", CateringSaleOrderQueryV1_1Output.class);		

		if (output == null || !SysConstants.OPEN_SUCCESS.equals(output.getCode())) {
			logger.error("餐饮订单查询失败，单号：" + orderId);
			if (output != null) {
				logger.error("餐饮订单查询失败：" + output.getMessage());
				if (SysConstants.NO_MERCHANT_CODE.equals(output.getCode())) {
					return new ModelAndView("error").addObject("err_message",
							SysConstants.NO_MERCHANT);
				}
			} else {
				return new ModelAndView("error").addObject("err_message",
						SysConstants.OPEN_ERROR_MESSAGE);
			}
		}
		
		CateringSaleOrderQueryV1_1Output.Result result = output.getResult();
		if (result == null) {
			 return new ModelAndView("error").addObject("err_message",
						SysConstants.OPEN_ERROR_MESSAGE);
		}
		List<OrderDetailV1_1> orderDetails = result.getOrderDetail();
		if (orderDetails != null) {
			for (OrderDetailV1_1 od : orderDetails) {
				productsNum += Integer.valueOf(od.getQty());
			}
		}
		String dispatchFare = result.getDispatchFare();
		if (!StringUtils.isEmpty(dispatchFare) && !"0.00".equals(dispatchFare)) {
			OrderDetailV1_1 od = new OrderDetailV1_1();
			od.setPrice(dispatchFare);
			od.setQty("1");
			od.setAmount(dispatchFare);
			od.setRemark("派送费");
			orderDetails.add(od);
			productsNum += 1;
		}
		
		result.setOrderNo(Function.getShowSaleOrderNo(result.getOrderNo()));
		
		switch (result.getStatus()) {
			case "-1": 
				result.setStatus("未下单"); 
				break;
			case "0": 
				if ("4".equals(result.getOrderType())) {// 外卖订单
					result.setStatus("已接受"); 
				} else {
					result.setStatus("未支付"); 
				}
				break;
			case "1": 
				result.setStatus("已完成"); 
				break;
			case "2": 
				result.setStatus("已取消"); 
				break;
			case "3":  // 3线上外卖下单未开单
				if ("1".equals(result.getPayStatus())) {
					result.setStatus("已下单");
				} else {
					result.setStatus("未支付");
				}
				break;
		}
		
		//餐饮类型(1堂吃2快餐3线下外卖4线上外卖)
 		switch (result.getOrderType()) {
			case "1": 
				result.setOrderType("堂食"); 
				break;
			case "2": 
				result.setOrderType("快餐"); 
				break;
			case "4": 
				result.setOrderType("外卖"); 
				break;
		}
 		String showPayType = "待定";
 		List<Payment> payments = result.getPayments();
		if (payments != null && payments.size() > 0) {
			String payType = payments.get(0).getPayType();
			if ("5".equals(payType)) {
				showPayType = "微信支付";
			} else if ("2".equals(payType)) {
				showPayType = "会员卡支付";
			}
		}
 		
		//请求微信 js api的完整页面地址
		String baseUrl = "http://"
				+ messageSource.getMessage(SysConstants.SERVICE_DNS , null,
						Locale.ENGLISH);
		baseUrl += httpRequest.getSession().getServletContext().getContextPath();
		StringBuffer tmpUrl = new StringBuffer();
		tmpUrl.append(baseUrl);
		tmpUrl.append("/dgd/order_detail");
		tmpUrl.append("?mid="+mid);
		tmpUrl.append("&orderId="+orderId);
		String url = tmpUrl.toString();		
		// 请求微信api的ticket
		AccessTokenInput jsInput = new AccessTokenInput();
		jsInput.setMid(mid);
		
		CommonResultOutput jsOutput = (CommonResultOutput) wizarposOpenRestClient.post(jsInput, "/weixin/ticket/js", CommonResultOutput.class);		
		if (jsOutput == null || SysConstants.OPEN_ERROR.equals(jsOutput.getCode())) {
			return new ModelAndView("error").addObject("err_message",
					SysConstants.OPEN_ERROR);
		} else if (SysConstants.NO_MERCHANT_CODE.equals(jsOutput.getCode())) {
			return new ModelAndView("error").addObject("err_message",
					SysConstants.NO_MERCHANT);
		} 
		
		Map<String, String> jsresult = (Map<String, String>) jsOutput.getResult();
		String jsTicket = jsresult.get("ticket");
		String appId = jsresult.get("appid");
		//微信 js config 签名
		Map<String, String> ret = WxSignUtil.commonSign(jsTicket, url,
				WxSignUtil.createTimestamp());
				
		return new ModelAndView("dgd_order/order_detail")
			.addObject("mid", mid)
			.addObject("shopMid", result.getShopMid())
			.addObject("orderId", orderId)
			.addObject("productsNum", productsNum)
			.addObject("order", result)
			.addObject("payType", showPayType)
			.addObject("appId", appId)
			.addAllObjects(ret);
	}

	/**
	 * 扫码确认下单
	 * 
	 * @param mid
	 * @param openId
	 * @param orderId
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "/order_confirm")
	public @ResponseBody RespMessage orderConfirm(
			@RequestParam(value = "orderId", required = true) String orderId,
			@RequestParam(value = "mid", required = true) String mid,
			@RequestParam(value = "tableId", required = true) String tableId,
			HttpServletRequest httpRequest) {
		RespMessage res = new RespMessage();	
		
		String cardId = (String) httpRequest.getSession().getAttribute("mrtCardId");
		if (StringUtils.isEmpty(cardId)) {//session过期，跳转到登录注册页面
			res.setCode(2);
			return res;	
		}
		String shopMid = null;
		GetTabelIdInput getTabelIdInput = new GetTabelIdInput();
		getTabelIdInput.setMid(mid);
		getTabelIdInput.setTicketId(MD5Util.MD5Encode(tableId, "UTF-8"));
		GetTabelIdOutput getTabelIdOutput = (GetTabelIdOutput) wizarposOpenRestClient.post(getTabelIdInput, "/dzx/getTabelId", GetTabelIdOutput.class);
		if (getTabelIdOutput != null && "0".equals(getTabelIdOutput.getCode()) && getTabelIdOutput.getResult() != null) {
			tableId = getTabelIdOutput.getResult().getTabelId();
			shopMid = getTabelIdOutput.getResult().getTabelId();
		} else {
			logger.error("请求开放平台获取桌号失败");
			res.setCode(1);
			res.setMessage("系统错误，点餐失败");
			return res;	
		}
		
		CateringSaleOrderQueryInput input = new CateringSaleOrderQueryInput();
		input.setMid(mid);
		input.setOrderId(orderId);
		CateringSaleOrderQueryOutput output = (CateringSaleOrderQueryOutput) wizarposOpenRestClient.post(input, "/catering/saleorder/query", CateringSaleOrderQueryOutput.class);		

		if (output == null || !SysConstants.OPEN_SUCCESS.equals(output.getCode())) {
			logger.error("餐饮订单查询失败，单号：" + orderId);
			if (output == null) {
				res.setCode(1);
				res.setMessage(SysConstants.OPEN_ERROR_MESSAGE);
			} else {
				logger.error("餐饮订单查询失败：" + output.getMessage());
				res.setCode(1);
				res.setMessage(output.getMessage());
			}
			return res;
		}
		
		CanyinSalesOrderSubmitInput inputUpdate = new CanyinSalesOrderSubmitInput();
		inputUpdate.setMid(mid);
		inputUpdate.setOrderId(orderId);
		inputUpdate.setOrderSource("2");
		inputUpdate.setOrderType("1");
		inputUpdate.setStatus("0");
		inputUpdate.setPayStatus("0");
		inputUpdate.setPrint(true);
		inputUpdate.setCardId(cardId);
		List<String> tables = new ArrayList<String>();
		tables.add(tableId);
		inputUpdate.setTableId(tables);
		CanyinSalesOrderSubmitOutput outputUpdate = (CanyinSalesOrderSubmitOutput) wizarposOpenRestClient.post(inputUpdate, "/dzx/saleorder/submit", CanyinSalesOrderSubmitOutput.class);		

		if (outputUpdate != null && "0".equals(outputUpdate.getCode())) {
			res.setCode(0);
			res.setObj(orderId);
		} else if (outputUpdate == null) {
			logger.error("餐饮订单修改失败，单号：" + orderId);
			logger.error("餐饮订单修改失败");
			res.setCode(1);
			res.setMessage(SysConstants.OPEN_ERROR_MESSAGE);
		} else {
			logger.error("餐饮订单修改失败，单号：" + orderId);
			logger.error("餐饮订单修改失败：" + outputUpdate.getMessage());
			res.setCode(1);
			if ("60025".equals(outputUpdate.getCode())) {
				res.setMessage("餐桌不可用");
			} else {
				res.setMessage(outputUpdate.getMessage());
			}
		} 
		return res;
	}
	
	/**
	 * 取消订单
	 * 
	 * @param mid
	 * @param openId
	 * @param orderId
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "/order_cancel")
	public @ResponseBody RespMessage orderCancel(
			@RequestParam(value = "orderId", required = true) String orderId,
			@RequestParam(value = "mid", required = true) String mid,
			HttpServletRequest httpRequest) {
		RespMessage res = new RespMessage();	
		
		String openId = (String) httpRequest.getSession().getAttribute("openId");
		String cardId = (String) httpRequest.getSession().getAttribute("mrtCardId");
		if (StringUtils.isEmpty(openId) || StringUtils.isEmpty(cardId)) {//session过期，跳转到登录注册页面
			res.setCode(2);
			return res;	
		}
		
		CanyinSalesOrderSubmitInput input = new CanyinSalesOrderSubmitInput();
		input.setMid(mid);
		input.setOrderId(orderId);
		input.setOrderSource("2");
		input.setOrderType("1");
		input.setStatus("2");
		input.setCardId(cardId);
		// 请求开放平台获取appId
		MerchantDefQueryInput merchantDefQueryInput = new MerchantDefQueryInput();
		merchantDefQueryInput.setMid(mid);
		MerchantDefQueryOutput merchantDefOuptut = (MerchantDefQueryOutput) wizarposOpenRestClient.post(merchantDefQueryInput, "/merchantdef/info", MerchantDefQueryOutput.class);
		if (merchantDefOuptut != null && "0".equals(merchantDefOuptut.getCode())) {
			MerchantDef merchant = merchantDefOuptut.getResult();
			StringBuffer url = new StringBuffer("https://open.weixin.qq.com/connect/oauth2/authorize?appid=");
			url.append(merchant.getWeixinAppId());
			url.append("&redirect_uri=http%3a%2f%2f");
			url.append(messageSource.getMessage(SysConstants.SERVICE_DNS, null,
					Locale.ENGLISH));
			String path = httpRequest.getContextPath();
			path = path.replace("/", "");
			url.append("%2f" + path +"%2foauth%2fcatering_menuinfo&response_type=code&scope=snsapi_base&state=");
			url.append(mid);
			url.append("ORDERID");
			input.setUrl(url.toString());
		}
		CanyinSalesOrderSubmitOutput output = (CanyinSalesOrderSubmitOutput) wizarposOpenRestClient.post(input, "/dzx/saleorder/submit", CanyinSalesOrderSubmitOutput.class);		

		if (output == null || !SysConstants.OPEN_SUCCESS.equals(output.getCode())) {
			logger.error("餐饮订单修改失败，单号：" + orderId);
			logger.error("餐饮订单修改失败：" + output.getMessage());
			if (SysConstants.NO_MERCHANT_CODE.equals(output.getCode())) {
				res.setCode(1);
				res.setMessage(SysConstants.NO_MERCHANT);
			} else {
				res.setCode(1);
				res.setMessage(SysConstants.OPEN_ERROR_MESSAGE);
			}
		}	
		
		res.setCode(0);
		res.setObj(orderId);
		
		return res;
	}
	
	/**
	 * 预下单结果
	 * 
	 * @param mid
	 * @param orderId
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "/order_pre_ok")
	public ModelAndView orderPreOk(
			@RequestParam(value = "orderId", required = true) String orderId,
			@RequestParam(value = "mid", required = true) String mid,
			HttpServletRequest httpRequest) {
		
		//请求微信 js api的完整页面地址
		String baseUrl = "http://"
				+ messageSource.getMessage(SysConstants.SERVICE_DNS , null,
						Locale.ENGLISH);
		baseUrl += httpRequest.getSession().getServletContext().getContextPath();
		StringBuffer tmpUrl = new StringBuffer();
		tmpUrl.append(baseUrl);
		tmpUrl.append("/dgd/order_pre_ok");
		tmpUrl.append("?mid="+mid);
		tmpUrl.append("&orderId="+orderId);
		String url = tmpUrl.toString();		
		// 请求微信api的ticket
		AccessTokenInput jsInput = new AccessTokenInput();
		jsInput.setMid(mid);
		
		CommonResultOutput jsOutput = (CommonResultOutput) wizarposOpenRestClient.post(jsInput, "/weixin/ticket/js", CommonResultOutput.class);		
		if (jsOutput == null || SysConstants.OPEN_ERROR.equals(jsOutput.getCode())) {
			return new ModelAndView("error").addObject("err_message",
					SysConstants.OPEN_ERROR);
		} else if (SysConstants.NO_MERCHANT_CODE.equals(jsOutput.getCode())) {
			return new ModelAndView("error").addObject("err_message",
					SysConstants.NO_MERCHANT);
		} 
		
		Map<String, String> jsresult = (Map<String, String>) jsOutput.getResult();
		String jsTicket = jsresult.get("ticket");
		String appId = jsresult.get("appid");
		//微信 js config 签名
		Map<String, String> ret = WxSignUtil.commonSign(jsTicket, url,
				WxSignUtil.createTimestamp());
				
		return new ModelAndView("dgd_order/order_pre_ok")
		.addObject("mid", mid)
		.addObject("orderId", orderId)
		.addObject("appId", appId)
		.addAllObjects(ret);
	}
	
	/**
	 * 订单列表
	 * 
	 * @param mid
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "/my_orders")
	public ModelAndView myOrders(
			@RequestParam(value = "mid", required = true) String mid,
			HttpServletRequest httpRequest) {
		String cardId = (String) httpRequest.getSession().getAttribute("mrtCardId");
		if (StringUtils.isEmpty(cardId)) {//session过期，跳转到登录注册页面
			return new ModelAndView("forward:/vip/login");
		}
		
		CateringSaleOrderListQueryInput input = new CateringSaleOrderListQueryInput();
		input.setCardId(cardId);
		input.setMid(mid); 
		//input.setPageNo(pageNo);
		CateringSaleOrderListQueryOutput output = (CateringSaleOrderListQueryOutput) wizarposOpenRestClient.post(input, "/catering/saleorder/list/query", CateringSaleOrderListQueryOutput.class);							
		if (output == null) {//请求开放平台出错
			return new ModelAndView("error").addObject("err_message", "系统错误");
		}

		String code = output.getCode();
		if ("60001".equals(code)) {//60001非法慧商户号
			return new ModelAndView("error").addObject("err_message", "该商户不存在。");
		} else if ("60070".equals(code)) {//60070 此商户下不存在此会员	
			return new ModelAndView("redirect:/vip/receiveCard?mid=" + mid);//前往会员卡领取页面
		} else if ("60037".equals(code)) {//60037非法的页码
			return new ModelAndView("error").addObject("err_message", "非法的页码");
		} else if (!SysConstants.OPEN_SUCCESS.equals(code)) {
			logger.error(output.getMessage());
			return new ModelAndView("error").addObject("err_message", "系统异常");
		}
		
		//0 操作成功				
		List<CateringSaleOrderDto> caterSaleOrderList = output.getSaleOrderList();		

		List<CateringReOrderView> orderList = new ArrayList<CateringReOrderView>();
		List<CateringReOrderView> endedList = new ArrayList<CateringReOrderView>();

		if (caterSaleOrderList.size() > 0) {
		}
		
		for (CateringSaleOrderDto obj : caterSaleOrderList) {
		CateringReOrderView reOrderView = new CateringReOrderView();
		try {
			BeanUtils.copyProperties(reOrderView, obj);
		} catch (IllegalAccessException | InvocationTargetException e) {
			e.printStackTrace();
		}			
		reOrderView.setShowOrderId(Function.getShowWxOrderNo(obj.getShowOrderId()));			
		
		if (StringUtils.isEmpty(obj.getTableNo())) {
			reOrderView.setTable("待定");
		}
		//(-1用户预下单商户不会感知 0开单 1结账 2撤单 3线上外卖下单未开单)
		if ("0".equals(obj.getStatus())) {
			if ("4".equals(obj.getCarterType())) { // 外卖订单
				reOrderView.setStatus("已接受");
			} else {
				reOrderView.setStatus("未支付");
			}
			orderList.add(reOrderView);				
		} else if ("-1".equals(obj.getStatus())) {
			reOrderView.setStatus("未下单");
			orderList.add(reOrderView);				
		} else if ("1".equals(obj.getStatus())) {
			reOrderView.setStatus("已付款");
			endedList.add(reOrderView);				
		} else if ("2".equals(obj.getStatus())) {
			reOrderView.setStatus("已取消");
			endedList.add(reOrderView);				
		} else if ("3".equals(obj.getStatus())) {
			if ("1".equals(obj.getPayStatus())) {
				reOrderView.setStatus("已下单");
			} else {
				reOrderView.setStatus("未支付");
			}
			orderList.add(reOrderView);				
		}
	}
	
	Collections.sort(orderList, new Comparator<CateringReOrderView>() {
		public int compare(CateringReOrderView a, CateringReOrderView b) {
			return b.getCreateTime().compareTo(a.getCreateTime());
		}
	});
	
	Collections.sort(endedList, new Comparator<CateringReOrderView>() {
		public int compare(CateringReOrderView a, CateringReOrderView b) {
			return b.getCreateTime().compareTo(a.getCreateTime());
		}
	});
		
	return new ModelAndView("dgd_order/my_orders")
				.addObject("orderList", orderList)
				.addObject("endedList", endedList)
				.addObject("mid", mid);
	}

	@RequestMapping(value = "/topay")
	public ModelAndView topay(
			@RequestParam(value = "orderId", required = true) String orderId,
			@RequestParam(value = "mid", required = true) String mid,
			HttpServletRequest httpRequest) throws UnsupportedEncodingException {

		String openId = (String) httpRequest.getSession()
				.getAttribute("openId");
		String cardId = (String) httpRequest.getSession().getAttribute(
				"mrtCardId");
		if (StringUtils.isEmpty(openId) || StringUtils.isEmpty(cardId))
		{// session过期，跳转到登录注册页面
			return new ModelAndView("forward:/vip/login");
		}
		Map<String, Object> data = new HashMap<String, Object>();

		CateringSaleOrderQueryInput input = new CateringSaleOrderQueryInput();
		input.setMid(mid);
		input.setOrderId(orderId);
		CateringSaleOrderQueryOutput output = (CateringSaleOrderQueryOutput) wizarposOpenRestClient.post(input, "/catering/saleorder/query", CateringSaleOrderQueryOutput.class);		

		if (output == null || !SysConstants.OPEN_SUCCESS.equals(output.getCode())) {
			logger.error("餐饮订单查询失败，单号：" + orderId);
			if (output != null) {
				logger.error("餐饮订单查询失败：" + output.getMessage());
				if (SysConstants.NO_MERCHANT_CODE.equals(output.getCode())) {
					return new ModelAndView("error").addObject("err_message",
							SysConstants.NO_MERCHANT);
				}
			} else {
				return new ModelAndView("error").addObject("err_message",
						SysConstants.OPEN_ERROR_MESSAGE);
			}
		}
		SaleOrder result = output.getResult();

		List<TicketInfoPayUse> tickets = wPosHttpClient.getPayUseTickets(mid, cardId);
		if (tickets != null) {
			data.put("ticketNum", tickets.size());
		} else {
			data.put("ticketNum", 0);
		}
		data.put("cashList", tickets);
		data.put("order", result);
		data.put("orderId", orderId);
		data.put("mid", mid);
		return new ModelAndView("dgd_order/order_pay", data);	
	}

	/**
	 * 下单结果
	 * 
	 * @param mid
	 * @param orderId
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "/order_ok")
	public ModelAndView orderOk(
			@RequestParam(value = "orderId", required = true) String orderId,
			@RequestParam(value = "mid", required = true) String mid,
			HttpServletRequest httpRequest)
	{
		return new ModelAndView("dgd_order/order_ok").addObject("mid", mid)
				.addObject("orderId", orderId);
	}

	/**
	 * 进入点餐
	 * 
	 * @param mid
	 * @param dateTime
	 * @return
	 */
	@RequestMapping(value = "/tomenu", method = RequestMethod.GET)
	@ResponseBody
	public ModelAndView toMenu(
			@RequestParam(value = "tableId", required = false) String tableId,
			@RequestParam(value = "mid", required = true) String mid,
			@RequestParam(value = "orderId", required = false) String orderId,
			@RequestParam(value = "startMenu", required = false) String startMenu,
			@RequestParam(value = "shopMid", required = false) String shopMid,
			HttpServletRequest httpRequest) {
		String openId = (String) httpRequest.getSession().getAttribute("openId");
		if (StringUtils.isEmpty(openId)) { //session过期，跳转到登录注册页面
			return new ModelAndView("forward:/vip/login");
		}
		Map<String, Object> data = new HashMap<String, Object>();
		// 从session中获取会员卡编号
		String cardId = (String) httpRequest.getSession().getAttribute("mrtCardId");
		if (StringUtils.isEmpty(cardId)) {
			// 请求开放平台查询会员卡信息
			WeChartMemberInfoQueryInput memberInfoQueryInput = new WeChartMemberInfoQueryInput();
			memberInfoQueryInput.setMid(mid);
			memberInfoQueryInput.setOpenId(openId);
			WeChartMemberInfoQueryOutput memberInfoQueryOutput = (WeChartMemberInfoQueryOutput) wizarposOpenRestClient.post(memberInfoQueryInput, "/wechart/info/query", WeChartMemberInfoQueryOutput.class);
			if (memberInfoQueryOutput != null && "0".equals(memberInfoQueryOutput.getCode())) {
				WeChartMemberInfoQueryOutput.Result result = memberInfoQueryOutput.getResult();
				if (result != null) {
					cardId = result.getId();
					httpRequest.getSession().setAttribute("mrtCardNo", result.getCardNo());
					httpRequest.getSession().setAttribute("mrtCardId", cardId);	
					if (StringUtils.isEmpty(result.getUserName()) || StringUtils.isEmpty(result.getMobileNo())) {
						// 会员卡存在未激活，用户名和手机号有空值，激活会员卡
						return new ModelAndView("forward:/vip/receiveCard");
					}
				} else {
					return new ModelAndView("error").addObject("err_message",
							SysConstants.OPEN_ERROR_MESSAGE);
				}
			} else if (memberInfoQueryOutput == null) {// 请求开放平台失败
				return new ModelAndView("error").addObject("err_message",
						SysConstants.OPEN_ERROR_MESSAGE);
			} else if ("60001".equals(memberInfoQueryOutput.getCode())) {// 60001 	非法慧商户号
				return new ModelAndView("error").addObject("err_message",
						SysConstants.NO_MERCHANT);
			} else if ("60007".equals(memberInfoQueryOutput.getCode())) {// 60007	会员不存在
				return new ModelAndView("forward:/vip/receiveCard");
			} else {
				logger.error("code: " + memberInfoQueryOutput.getCode());
				logger.error("message: " + memberInfoQueryOutput.getMessage());
				return new ModelAndView("error").addObject("err_message",
						SysConstants.OPEN_ERROR_MESSAGE);
			}
		}
		String isMainStore = "0";
		// 请求开放平台获取商户信息
		MerchantDefQueryInput merchantDefQueryInput = new MerchantDefQueryInput();
		merchantDefQueryInput.setMid(mid);
		MerchantDefQueryOutput merchantDefQueryOutput = (MerchantDefQueryOutput) wizarposOpenRestClient.post(merchantDefQueryInput,"/merchantdef/info",MerchantDefQueryOutput.class);
		if (merchantDefQueryOutput != null && SysConstants.OPEN_SUCCESS.equals(merchantDefQueryOutput.getCode())) {
			MerchantDef merchantDef = merchantDefQueryOutput.getResult();
			isMainStore = merchantDef.getIsVirtualMainStore();
			data.put("merchantName", merchantDef.getMerchantName());
			data.put("isMainStore", isMainStore);
			data.put("bannerImage", merchantDef.getBannerImage());
		} else {
			logger.error("请求开放平台获取商户信息失败");
			if (merchantDefQueryOutput == null) {
				logger.error("系统错误");
			} else {
				logger.error("code：" + merchantDefQueryOutput.getCode());
				logger.error("message：" + merchantDefQueryOutput.getMessage());
			}
			return new ModelAndView("error").addObject("err_message",
					SysConstants.OPEN_ERROR_MESSAGE);
			
		}
		// 请求微信 js api的完整页面地址
		String baseUrl = getBaseURL(httpRequest);
		StringBuffer tmpUrl = new StringBuffer();
		tmpUrl.append(baseUrl);
		tmpUrl.append("/dgd/tomenu");
		tmpUrl.append("?mid=");
		tmpUrl.append(mid);
		if (!StringUtils.isEmpty(startMenu))
		{
			tmpUrl.append("&startMenu=");
			tmpUrl.append(startMenu);
		}
		if (!StringUtils.isEmpty(orderId))
		{
			tmpUrl.append("&orderId=");
			tmpUrl.append(orderId);
		}
		if (!StringUtils.isEmpty(shopMid)) {
			tmpUrl.append("&shopMid=");
			tmpUrl.append(shopMid);	
		}
		if (!StringUtils.isEmpty(tableId))
		{
			tmpUrl.append("&tableId=");
			tmpUrl.append(tableId);
			
			// 请求开放平台获取餐桌详细
			CateringTableDetailV1_1Input tableDetailInput = new CateringTableDetailV1_1Input();
			tableDetailInput.setTableId(tableId);
			CateringTableDetailOutput tableDetailOutput = (CateringTableDetailOutput) wizarposOpenRestClient.postV1_1(tableDetailInput, "/canyin/table/detail", CateringTableDetailOutput.class);
			if (tableDetailOutput != null
					&& "0".equals(tableDetailOutput.getCode())
					&& tableDetailOutput.getResult() != null) {
				CateringTableDetailOutput.Result tableDef = tableDetailOutput.getResult();
				data.put("tableName", tableDef.getTableName());
				shopMid = tableDef.getMid();
			} else {
				logger.error("请求开放平台获取餐桌详细失败");
				if (tableDetailOutput == null) {
					logger.error("tableId：" + tableId);
				} else {
					logger.error("code：" + tableDetailOutput.getCode());
					logger.error("message：" + tableDetailOutput.getMessage());
				}
				return new ModelAndView("error").addObject("err_message",
						SysConstants.OPEN_ERROR_MESSAGE); 
			}
		}
		String url = tmpUrl.toString();
		// 请求微信api的ticket
		AccessTokenInput jsInput = new AccessTokenInput();
		jsInput.setMid(mid);
		CommonResultOutput jsOutput = (CommonResultOutput) wizarposOpenRestClient
				.post(jsInput, "/weixin/ticket/js", CommonResultOutput.class);
		if (jsOutput == null
				|| SysConstants.OPEN_ERROR.equals(jsOutput.getCode()))
		{
			return new ModelAndView("error").addObject("err_message",
					SysConstants.OPEN_ERROR);
		} else if (SysConstants.NO_MERCHANT_CODE.equals(jsOutput.getCode()))
		{
			return new ModelAndView("error").addObject("err_message",
					SysConstants.NO_MERCHANT);
		} else
		{
			Map<String, String> result = (Map<String, String>) jsOutput
					.getResult();
			String jsTicket = result.get("ticket");
			String appid = result.get("appid");
			data.put("appId", appid);
			Map<String, String> ret = WxSignUtil.commonSign(jsTicket, url,
					WxSignUtil.createTimestamp());
			data.putAll(ret);
		}
		if (!StringUtils.isEmpty(orderId)) { // 已有订单从订单中获取门店商户号
			WxSaleOrderQueryInput wxSaleOrderQueryInput = new WxSaleOrderQueryInput();
			wxSaleOrderQueryInput.setOrderId(orderId);
			WxSaleOrderQueryV1_1Output saleOrderQueryOutput = (WxSaleOrderQueryV1_1Output) wizarposOpenRestClient.postV1_1(wxSaleOrderQueryInput, "/wx_shop/wxSaleOrderQuery", WxSaleOrderQueryV1_1Output.class);
			
			if (saleOrderQueryOutput == null || !SysConstants.OPEN_SUCCESS.equals(saleOrderQueryOutput.getCode())) {//系统错误	
				if (saleOrderQueryOutput == null) {
					logger.error("请求开放平台销售单查询接口失败");
					logger.error("orderId："+orderId);
				} else {
					logger.error("code：" + saleOrderQueryOutput.getCode());
					logger.error("message：" + saleOrderQueryOutput.getMessage());
				}
				return new ModelAndView("error").addObject("err_message", SysConstants.OPEN_ERROR_MESSAGE);
			}		
			WxSaleOrderQueryV1_1Output.Result order = saleOrderQueryOutput.getResult();
			shopMid = order.getShopMid();
		}
		// 总分店模式：选择门店
		if (StringUtils.isEmpty(tableId) && StringUtils.isEmpty(orderId) &&  !"1".equals(startMenu) && "1".equals(isMainStore)) {
			// 获取商家信息
			GetShopInfoInput getShopInfoInput = new GetShopInfoInput();
			getShopInfoInput.setMid(mid);
			getShopInfoInput.setType("2"); // 2外卖、堂食
			GetShopInfoOutput getShopInfoOutput = (GetShopInfoOutput) wizarposOpenRestClient.post(getShopInfoInput, "/dzx/getShopInfo", GetShopInfoOutput.class);								
			if (getShopInfoOutput == null) {
				logger.error("请求开放平台获取商户信息（fid下mid集合）或门店信息（mid下sn集合）接口失败");
				logger.error("mid："+mid);
				return new ModelAndView("error").addObject("err_message", SysConstants.OPEN_ERROR_MESSAGE);			
			} else if (!SysConstants.OPEN_SUCCESS.equals(getShopInfoOutput.getCode())) {
				logger.error("code：" + getShopInfoOutput.getCode());
				logger.error("message：" + getShopInfoOutput.getMessage());
				return new ModelAndView("error").addObject("err_message", getShopInfoOutput.getMessage());	
			}
			List<ShopInfoPair> shopInfoPairs = getShopInfoOutput.getResult().getShopInfoPairs();
			data.put("shopInfoPairs", shopInfoPairs);
			if (shopInfoPairs.size() < 2) { // 总店下无分店或仅有一家分店
				data.put("shopMid", shopInfoPairs.get(0).getMid());
			} else {
				JSONArray arr = new JSONArray();
				for (ShopInfoPair s : shopInfoPairs) {
					JSONObject json = new JSONObject();
					json.put("lon", s.getLon());
					json.put("lat", s.getLat());
					json.put("mid", s.getMid());
					json.put("name", s.getName());
					json.put("distance", s.getDistance());
					json.put("logoImage", s.getLogoImage());
					json.put("merchantAddr", s.getMerchantAddr());
					json.put("merchantTel", s.getMerchantTel());
					json.put("deliveryStartFare", s.getDeliveryStartFare());
					json.put("deliveryFixedFare", s.getDeliveryFixedFare());
					arr.add(json);
				}
				data.put("shopInfoPairs", arr.toJSONString());
				data.put("mid", mid);
				data.put("isWaimai", "0");
				return new ModelAndView("waimai/start_menu", data);
			}
		}
		
		if (StringUtils.isEmpty(shopMid)) {
			shopMid = mid;
		}
		ProductCategorySyncInput productCategorySyncInput = new ProductCategorySyncInput();
		productCategorySyncInput.setMid(shopMid);
		ProductCategorySyncOutput productCategorySyncOutput = (ProductCategorySyncOutput) wizarposOpenRestClient
				.post(productCategorySyncInput, "/product/category",
						ProductCategorySyncOutput.class);
		
		if (productCategorySyncOutput == null || !SysConstants.OPEN_SUCCESS.equals(productCategorySyncOutput.getCode())) {
			logger.error("餐饮品类查询失败，商户号：" + mid);
			if (productCategorySyncOutput != null) {
				logger.error("餐饮品类查询失败：" + productCategorySyncOutput.getMessage());
				if (SysConstants.NO_MERCHANT_CODE.equals(productCategorySyncOutput.getCode())) {
					return new ModelAndView("error").addObject("err_message",
							SysConstants.NO_MERCHANT);
				} else {
					return new ModelAndView("error").addObject("err_message",
							productCategorySyncOutput.getMessage());
				}
			} else {
				return new ModelAndView("error").addObject("err_message",
						SysConstants.OPEN_ERROR_MESSAGE);
			}
		}
		
		List<Category> categoryList = productCategorySyncOutput
				.getResult();

		Map<String, Object> products = new HashMap<String, Object>();
		// 查询第一个品类的商品
		boolean next = true;
		for (Category category : categoryList)
		{
			String isVirtual = category.getFlag();
			String categoryId = category.getId();
			String categoryCode = category.getCode();
			List<ErpProduct> productList = new ArrayList<ErpProduct>();
			if (next) {
				MerchandiseSyncInput merchandiseSyncInput = new MerchandiseSyncInput();
				merchandiseSyncInput.setMid(shopMid);
				merchandiseSyncInput.setCategoryId(categoryId);
				
				MerchandiseSyncOutput merchandiseSyncOutput = null;
				if ("1".equals(isVirtual)) {
					merchandiseSyncOutput = (MerchandiseSyncOutput) wizarposOpenRestClient
							.post(merchandiseSyncInput, "/product/virtual",
									MerchandiseSyncOutput.class);
				} else {
					merchandiseSyncOutput = (MerchandiseSyncOutput) wizarposOpenRestClient
						.post(merchandiseSyncInput, "/product/merchandise",
								MerchandiseSyncOutput.class);
				}
	
				if (merchandiseSyncOutput == null || !SysConstants.OPEN_SUCCESS.equals(merchandiseSyncOutput.getCode())) {
					logger.error("餐饮商品查询失败，商户号：" + shopMid + ",品类ID：" + categoryId);
					if (merchandiseSyncOutput != null) {
						logger.error("餐饮商品查询失败：" + merchandiseSyncOutput.getMessage());
						if (SysConstants.NO_MERCHANT_CODE.equals(merchandiseSyncOutput.getCode())) {
							return new ModelAndView("error").addObject("err_message",
									SysConstants.NO_MERCHANT);
						} else {
							return new ModelAndView("error").addObject("err_message",
									merchandiseSyncOutput.getMessage());
						}
					} else {
						return new ModelAndView("error").addObject("err_message",
								SysConstants.OPEN_ERROR_MESSAGE);
					}
				}
				
				List<Merchandise> productListTemp = merchandiseSyncOutput
						.getResult();
				// 处理价格分-元，图片路径
				for (Merchandise prt : productListTemp)
				{
					ErpProduct ep = new ErpProduct();
					ep.setId(prt.getProductId());
					ep.setCode(prt.getCode());
					ep.setName(prt.getName());
					ep.setPrice(prt.getPrice());
					ep.setShowMemPrice(prt.getMemberPrice());
					// 商品图片处理
					// 若无图片则设置默认图片（dgd_order/menu 页面内引用工程默认图片  images/default.jpg）
					if (!StringUtils.isEmpty(prt.getPicUrl())) {
						ep.setPicUrl(Function.dealGridPicUrl(prt.getPicUrl().split(",")[0], 150, 150));
					}
					ep.setProductAtts(prt.getProductAtts());
					ep.setUnit(prt.getUnit());
					productList.add(ep);
				}
				next = false;
			}
			products.put("topten" + categoryCode, productList);
		}

		data.put("dns", messageSource.getMessage(SysConstants.SERVICE_DNS, null,
				Locale.ENGLISH));

		List<MrtMerchantCarousel> carousels = mrtMerchantCarouselService.getMrtMerchantCarouselList(mid);
		String carouselBaseUrl = getCaruselBaseURL(httpRequest);
		if (carousels != null && carousels.size() > 0) {
			if (carousels.size() == 1) {
				 data.put("bannerPath1", carouselBaseUrl + carousels.get(0).getFilePaths());
				 data.put("bannerUrl1", carousels.get(0).getFileUrl());
			} else if (carousels.size() == 2) {
				 data.put("bannerPath1", carouselBaseUrl + carousels.get(0).getFilePaths());
				 data.put("bannerPath2", carouselBaseUrl + carousels.get(1).getFilePaths());
				 data.put("bannerUrl1", carousels.get(0).getFileUrl());
				 data.put("bannerUrl2", carousels.get(1).getFileUrl());
			} else if (carousels.size() > 2) {
				 data.put("bannerPath1", carouselBaseUrl + carousels.get(0).getFilePaths());
				 data.put("bannerPath2", carouselBaseUrl + carousels.get(1).getFilePaths());
				 data.put("bannerPath3", carouselBaseUrl + carousels.get(2).getFilePaths());
				 data.put("bannerUrl1", carousels.get(0).getFileUrl());
				 data.put("bannerUrl2", carousels.get(1).getFileUrl());
				 data.put("bannerUrl3", carousels.get(2).getFileUrl());
			}
		}
		data.put("products", products);
		data.put("categoryList", categoryList);
		data.put("tableId", tableId);
		data.put("orderId", orderId);
		data.put("cardId", cardId);
		data.put("mid", mid);
		data.put("shopMid", shopMid);
		Utils.setSessionToken(httpRequest);
		return new ModelAndView("dgd_order/menu", data);
	}
	
	/**
	 * 获取餐椅menu页广告图片
	 * 
	 * @param mid
	 * @param url
	 * @param response
	 * @param httpRequest
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "/get_banner")
	public void getBanner(
			@RequestParam(value = "mid", required = true) String mid,
			@RequestParam(value = "url", required = true)String url, HttpServletResponse response,
			HttpServletRequest httpRequest) throws UnsupportedEncodingException {
		try {
			InputStream in = new FileInputStream(url);
			int i = in.available(); // 得到文件大小
			byte data[] = new byte[i];
			in.read(data); // 读数据
			in.close();
			response.setContentType("image/*"); // 设置返回的文件类型
			OutputStream out = response.getOutputStream(); // 得到向客户端输出二进制数据的对象
			out.write(data); // 输出数据
			out.close();
		} catch (Exception e) {
			logger.error(e);
		}
	}

	/**
	 * 获取相应品类下商品集合
	 * 
	 * @param mid
	 * @param categoryId
	 * @param categoryCode
	 * @param isVirtual
	 * @return
	 */
	@RequestMapping(value = "/get_products", method = RequestMethod.GET)
	@ResponseBody
	public RespMessage getProducts(
			@RequestParam(value = "mid", required = true) String mid,
			@RequestParam(value = "categoryId", required = true) String categoryId,
			@RequestParam(value = "isVirtual", required = true) String isVirtual) {
		RespMessage res = new RespMessage();

		MerchandiseSyncInput merchandiseSyncInput = new MerchandiseSyncInput();
		merchandiseSyncInput.setMid(mid);
		merchandiseSyncInput.setCategoryId(categoryId);
		
		MerchandiseSyncOutput merchandiseSyncOutput = null;
		if ("1".equals(isVirtual)) {
			merchandiseSyncOutput = (MerchandiseSyncOutput) wizarposOpenRestClient
					.post(merchandiseSyncInput, "/product/virtual",
							MerchandiseSyncOutput.class);
		} else {
			merchandiseSyncOutput = (MerchandiseSyncOutput) wizarposOpenRestClient
				.post(merchandiseSyncInput, "/product/merchandise",
						MerchandiseSyncOutput.class);
		}

		if (merchandiseSyncOutput == null || !SysConstants.OPEN_SUCCESS.equals(merchandiseSyncOutput.getCode())) {
			logger.error("餐饮商品查询失败，商户号：" + mid + ",品类ID：" + categoryId);
			if (merchandiseSyncOutput != null) {
				logger.error("餐饮商品查询失败：" + merchandiseSyncOutput.getMessage());
			} else {
				logger.error("请求开放平台餐饮商品查询接口失败");
			}
			res.setCode(2);
			res.setMessage("获取商品失败");
			return res;
		}
		List<ErpProduct> productList = new ArrayList<ErpProduct>();
		List<Merchandise> productListTemp = merchandiseSyncOutput
				.getResult();
		// 处理价格分-元，图片路径
		for (Merchandise prt : productListTemp)
		{
			ErpProduct ep = new ErpProduct();
			ep.setId(prt.getProductId());
			ep.setCode(prt.getCode());
			ep.setName(prt.getName());
			ep.setPrice(prt.getPrice());
			ep.setShowMemPrice(prt.getMemberPrice());
			// 商品图片处理
			// 若无图片则设置默认图片（dgd_order/menu 页面内引用工程默认图片  images/default.jpg）
			if (!StringUtils.isEmpty(prt.getPicUrl())) {
				ep.setPicUrl(Function.dealGridPicUrl(prt.getPicUrl().split(",")[0], 150, 150));
			}
			ep.setProductAtts(prt.getProductAtts());
			ep.setUnit(prt.getUnit());
			productList.add(ep);
		}
		res.setObj(productList);
		return res;
	}
	
	private String getBaseURL(HttpServletRequest httpRequest)
	{
		String baseUrl = "http://"
				+ messageSource.getMessage(SysConstants.SERVICE_DNS, null,
						Locale.ENGLISH);
		baseUrl += httpRequest.getSession().getServletContext()
				.getContextPath();
		return baseUrl;
	}
	
	private String getCaruselBaseURL(HttpServletRequest httpRequest)
	{
		String baseUrl = messageSource.getMessage(SysConstants.CAROUSEL_PATH, null,
								Locale.ENGLISH);
		return baseUrl;
	}

	/**
	 * 点单明细
	 * 
	 * @param mid
	 * @param openId
	 * @param orderId
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "/save_order")
	public ModelAndView saveOrder(
			@RequestParam(value = "tableId", required = false) String tableId,
			@RequestParam(value = "orderNum", required = true) String orderNum,
			@RequestParam(value = "sum", required = true) String sum,
			@RequestParam(value = "mid", required = true) String mid,
			@RequestParam(value = "orderDetail", required = true) String orderDetail,
			@RequestParam(value = "orderId", required = false) String orderId,// 继续点单
			HttpServletRequest httpRequest) throws IOException
	{
		String openId = (String) httpRequest.getSession()
				.getAttribute("openId");
		if (StringUtils.isEmpty(openId))
		{// session过期，跳转到登录注册页面
			return new ModelAndView("forward:/vip/login");
		}
		String token = (String) httpRequest.getSession().getAttribute("token");
		
		com.alibaba.fastjson.JSONArray detailArray = JSON
				.parseArray(orderDetail);
		List<ProductView> list = new ArrayList<ProductView>();
		List<ProductView> oldProducts = new ArrayList<ProductView>();
		// 已点餐金额
		String oldSum = "0.0";
		// 已点餐数量
		int oldProductsNum = 0;
		// 点餐数量
		int productsNum = 0;
		String status = null;
		if (!StringUtils.isEmpty(tableId)) {
			status = "0";
		}
		for (int i = 0; i < detailArray.size(); i++) {
			JSONObject detail = detailArray.getJSONObject(i);
			ProductView pv = new ProductView();
			pv.setI(String.valueOf(i));
			pv.setId(detail.getString("id"));
			pv.setName(URLDecoder.decode(detail.getString("name"), "UTF-8"));
			pv.setPrice(detail.getString("price"));
			pv.setNum(detail.getInteger("qty"));
			pv.setCode(detail.getString("code"));
			pv.setDesc(detail.getString("productRemark"));
			pv.setProductAttr(detail.getString("productAttr"));
			com.alibaba.fastjson.JSONArray proAttrs =  detail.getJSONArray("productAttrs");
			List<Map<String, Object>> productAttrs = null; 
			if (proAttrs != null) {
				productAttrs = new ArrayList<Map<String,Object>>();
				for (int j = 0; j < proAttrs.size(); j++) {
					productAttrs.add(proAttrs.getJSONObject(j));
				}
				pv.setProductAttrs(productAttrs);
			}
			productsNum += detail.getIntValue("qty");
			list.add(pv);
		}
		
		JSONArray savedDetails = new JSONArray();
		String totalRemark = "";
		if (!StringUtils.isEmpty(orderId)) {// 继续点餐
			CateringSaleOrderQueryInput input = new CateringSaleOrderQueryInput();
			input.setMid(mid);
			input.setOrderId(orderId);
			CateringSaleOrderQueryOutput output = (CateringSaleOrderQueryOutput) wizarposOpenRestClient.post(input, "/catering/saleorder/query", CateringSaleOrderQueryOutput.class);		
	
			if (output == null || !SysConstants.OPEN_SUCCESS.equals(output.getCode()) || output.getResult() == null) {
				logger.error("餐饮订单查询失败，单号：" + orderId);
				if (output != null) {
					logger.error("餐饮订单查询失败：" + output.getMessage());
					if (SysConstants.NO_MERCHANT_CODE.equals(output.getCode())) {
						return new ModelAndView("error").addObject("err_message",
								SysConstants.NO_MERCHANT);
					} else {
						return new ModelAndView("error").addObject("err_message",
								SysConstants.OPEN_ERROR_MESSAGE);
					}
				}
				return new ModelAndView("error").addObject("err_message",
						SysConstants.OPEN_ERROR_MESSAGE);
			}
			tableId = output.getResult().getTableId();
			List<OrderDetail> orderDetails = output.getResult().getOrderDetail();
			
			if (orderDetails != null) {
				for (int i = 0; i < orderDetails.size(); i++) {
					OrderDetail od = orderDetails.get(i);
					ProductView pv = new ProductView();
					pv.setI(String.valueOf(i));
					pv.setId(od.getProductId());
					pv.setName(od.getProductName());
					pv.setPrice(od.getPrice());
					pv.setNum(Integer.valueOf(od.getQty()));
					pv.setCode(od.getCode());
					String productAttr = "";
					String productRemark = "";
					String desc = od.getRemark().replaceFirst(od.getProductName(), "");
					int start = desc.indexOf("[");
					int end = desc.indexOf("]");					
					if (od.getProductAttrs() != null && od.getProductAttrs().size() != 0) {
						// 取第一个[]中的值
						if (start != -1 && end != -1) {
							productAttr = desc.substring(start+1, end);
							productRemark = desc.substring(end + 1);
							productRemark = productRemark.replace("[", "").replace("]", "");						
						}
					} else {
						if (start != -1 && end != -1) {
							productRemark = desc.substring(desc.indexOf("["), desc.indexOf("]"));
							productRemark = productRemark.replace("[", "").replace("]", "");
						}
					}
					// 备注
					pv.setDesc(productRemark);
					// 属性
					pv.setProductAttr(productAttr);
					pv.setProductAttrs(od.getProductAttrs());
					
					JSONObject detail = new JSONObject();
					detail.put("i", String.valueOf(i));
					detail.put("id", od.getProductId());
					detail.put("code", od.getCode());
					detail.put("name", od.getProductName());
					detail.put("price", od.getPrice());
					detail.put("qty", Integer.valueOf(od.getQty()));
					detail.put("productAttr", productAttr);
					detail.put("productRemark", productRemark);
					detail.put("productAttrs", od.getProductAttrs());
					savedDetails.add(detail);
					oldProducts.add(pv);
					oldProductsNum += Integer.valueOf(od.getQty());
				}
				
			}
			oldSum = output.getResult().getAmount();
			status = output.getResult().getStatus();
			totalRemark = output.getResult().getRemark();
		}

		// 总金额
		double totalSum = Float.parseFloat(sum) + Float.parseFloat(oldSum);
		
		return new  ModelAndView("dgd_order/saveorder")
			.addObject("products", list)
			.addObject("oldProducts", oldProducts)
			.addObject("sum", sum)
			.addObject("oldSum", oldSum)
			.addObject("totalSum", Utils.formatNumber(totalSum))
			.addObject("orderDate", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()))
			.addObject("productsNum", productsNum)
			.addObject("oldProductsNum", oldProductsNum)
			.addObject("oldProductsNum", oldProductsNum)
			.addObject("newdetails", orderDetail)
			.addObject("savedDetails", savedDetails.toJSONString())
			.addObject("tableId", tableId)
			.addObject("orderNum", orderNum)
			.addObject("order", "")
			.addObject("mid", mid)
			.addObject("orderId", orderId)
			.addObject("totalRemark", totalRemark)
			.addObject("status", status)
			.addObject("token", token);
	}
	
	/**
	 * 
	 * @param token
	 * @param tableId
	 * @param openId
	 * @param mid
	 * @param orderNum
	 * @param sum
	 * @param orderDetail
	 * @param reOrderId 预订单id
	 * @param httpRequest
	 * @param attributes
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "/order_submit")
	@ResponseBody
	public RespMessage orderSubmit(
			@RequestParam(value = "tableId", required = true) String tableId,
			@RequestParam(value = "mid", required = true) String mid,
			@RequestParam(value = "orderNum", required = true) String orderNum,
			@RequestParam(value = "sum", required = true) String sum,
			@RequestParam(value = "orderDetail", required = true) String orderDetail,
			@RequestParam(value = "olddetail", required = true) String olddetail,
			@RequestParam(value = "orderStatus", required = false) String orderStatus,
			@RequestParam(value = "reOrderId", required = false) String reOrderId,
			@RequestParam(value = "orderid", required = false) String orderid,
			@RequestParam(value = "remark", required = false) String remark,//add xudongdong
			@RequestParam(value = "scanFlag", required = true) String scanFlag,//add xudongdong
			@RequestParam(value = "token", required = true) String token,//add xudongdong
			@RequestParam(value = "shopMid", required = false) String shopMid,
			HttpServletRequest httpRequest) throws UnsupportedEncodingException {
		
		logger.info("submitmenu");
		
		RespMessage res = new RespMessage();		
		String cardId = (String) httpRequest.getSession().getAttribute("mrtCardId");
		String openId = (String) httpRequest.getSession().getAttribute("openId");
		if (StringUtils.isEmpty(cardId) || StringUtils.isEmpty(openId)) {//session过期，跳转到登录注册页面
			res.setCode(2);
			return res;	
		}
		logger.info("cardId="+cardId);
		if (Utils.isRepeatSubmit(httpRequest, token)) {
			res.setCode(1);
			res.setMessage("订单重复提交");
			return res;
		}
		if (reOrderId == null || reOrderId.isEmpty()) {// TODO 是否查看有无预订单

		} else {
			CateringOrderQueryInput input = new CateringOrderQueryInput();
			input.setMid(mid);
			input.setReOrderId(reOrderId);
			CateringOrderQueryOutput ouptut = (CateringOrderQueryOutput) wizarposOpenRestClient.post(input, "/catering/reorder/query", CateringOrderQueryOutput.class);							
			List<TableOrder> tableOrderList = ouptut.getResult();		
			if (tableOrderList.size() != 0 && !"1".equals(tableOrderList.get(0).getAuditFlag()) 
					&& !"0".equals(tableOrderList.get(0).getStatus())) {		
				//接受了的预订单，且未开桌的预定才可以在线点单
				res.setCode(1);
				res.setMessage("预定已经失效");
				return res;
			}
		}
		
		// 请求开放平台获取桌号	
		if ("1".equals(scanFlag)) {
			GetTabelIdInput getTabelIdInput = new GetTabelIdInput();
			getTabelIdInput.setMid(mid);
			getTabelIdInput.setTicketId(MD5Util.MD5Encode(tableId, "UTF-8"));
			GetTabelIdOutput getTabelIdOutput = (GetTabelIdOutput) wizarposOpenRestClient.post(getTabelIdInput, "/dzx/getTabelId", GetTabelIdOutput.class);
			if (getTabelIdOutput != null && "0".equals(getTabelIdOutput.getCode()) && getTabelIdOutput.getResult() != null) {
				tableId = getTabelIdOutput.getResult().getTabelId();
			} else {
				logger.error("请求开放平台获取桌号失败");
				res.setCode(1);
				res.setMessage("系统错误，点餐失败。");
				return res;	
			}
		}
		CanyinSalesOrderSubmitInput salesOrderSubmitInput = new CanyinSalesOrderSubmitInput();
		salesOrderSubmitInput.setMid(mid);
		salesOrderSubmitInput.setShopMid(shopMid);
		salesOrderSubmitInput.setOrderId(orderid);
		salesOrderSubmitInput.setReOrderId(reOrderId);
		salesOrderSubmitInput.setOrderType("1"); //堂吃
		salesOrderSubmitInput.setOrderSource("2"); //微信订单
		String status = "-1";
		if (!StringUtils.isEmpty(tableId)) {
			status = "0";
		}
		// 订单原状态
		if (!StringUtils.isEmpty(orderStatus)) {
			status = orderStatus;
		}
		if (!StringUtils.isEmpty(tableId)) {
			salesOrderSubmitInput.setTableId(Arrays.asList(tableId.split(",")));
		}
		salesOrderSubmitInput.setStatus(status);
		salesOrderSubmitInput.setAmount(sum);
		salesOrderSubmitInput.setOrderNum(orderNum);
		salesOrderSubmitInput.setPrint(true);
		salesOrderSubmitInput.setRemark(URLDecoder.decode(remark, "UTF-8"));
		salesOrderSubmitInput.setCardId(cardId);
		
		JSONArray details = new JSONArray();
		Map<String, Object> map = new HashMap<String, Object>();
		// 合并新订单中id和备注相同的商品
		JSONArray newDetail = JSON.parseArray(orderDetail);
		for (int i = 0; i < newDetail.size(); i++) {
			JSONObject newPro = newDetail.getJSONObject(i);
			// 商品id和备注相同则合并
			String key = newPro.getString("productId") + newPro.getString("remark");
			if (map.containsKey(key)) {
				JSONObject temp  = (JSONObject) map.get(key);
				int qty = Integer.valueOf(temp.getString("qty")) + Integer.valueOf(newPro.getString("qty"));
				temp.put("qty", String.valueOf(qty));
			} else {
				map.put(key, newPro);
			}
		}
		// 判断是否是预下单
		// -1 未下单  pos端未打印小票，订单可以修改，合并新旧订单
		if ("-1".equals(orderStatus)) {
			if (!StringUtils.isEmpty(olddetail)) {
				JSONArray oldDetail = JSON.parseArray(olddetail);
				for (int i = 0; i < oldDetail.size(); i++) {
					JSONObject oldPro = oldDetail.getJSONObject(i);
					// 商品id和备注相同则合并
					String key = oldPro.getString("productId") + oldPro.getString("remark");
					if (map.containsKey(key)) {
						JSONObject temp  = (JSONObject) map.get(key);
						int qty = Integer.valueOf(temp.getString("qty")) + Integer.valueOf(oldPro.getString("qty"));
						temp.put("qty", String.valueOf(qty));
					} else {
						map.put(key, oldPro);
					}
				}		
			}

		}
		for(Map.Entry<String, Object> entry : map.entrySet()) {
			details.add(entry.getValue());
		}
		List<CateringDetail> orderDetails = new ArrayList<CateringDetail>();
		for (int i = 0; i < details.size(); i++) {
			JSONObject od = details.getJSONObject(i);
			CateringDetail cateringDetail = new CateringDetail();
			cateringDetail.setProductId(od.getString("productId"));
			cateringDetail.setPrice(od.getString("price"));
			cateringDetail.setQty(od.getString("qty"));
			float amt = od.getFloat("price") * od.getInteger("qty");
			cateringDetail.setAmount(String.valueOf(amt));
			cateringDetail.setRemark(od.getString("remark"));
			orderDetails.add(cateringDetail);
		}
		salesOrderSubmitInput.setOrderDetail(orderDetails);
		// 请求开放平台获取appId
		MerchantDefQueryInput merchantDefQueryInput = new MerchantDefQueryInput();
		merchantDefQueryInput.setMid(mid);
		MerchantDefQueryOutput merchantDefOuptut = (MerchantDefQueryOutput) wizarposOpenRestClient.post(merchantDefQueryInput, "/merchantdef/info", MerchantDefQueryOutput.class);
		if (merchantDefOuptut != null && "0".equals(merchantDefOuptut.getCode())) {
			MerchantDef merchant = merchantDefOuptut.getResult();
			StringBuffer url = new StringBuffer("https://open.weixin.qq.com/connect/oauth2/authorize?appid=");
			url.append(merchant.getWeixinAppId());
			url.append("&redirect_uri=http%3a%2f%2f");
			url.append(messageSource.getMessage(SysConstants.SERVICE_DNS, null,
					Locale.ENGLISH));
			String path = httpRequest.getContextPath();
			path = path.replace("/", "");
			url.append("%2f" + path +"%2foauth%2fcatering_menuinfo&response_type=code&scope=snsapi_base&state=");
			url.append(mid);
			url.append("ORDERID");
			salesOrderSubmitInput.setUrl(url.toString());
		}
		CanyinSalesOrderSubmitOutput salesOrderSubmitOutput = (CanyinSalesOrderSubmitOutput) wizarposOpenRestClient.post(salesOrderSubmitInput, "/dzx/saleorder/submit", CanyinSalesOrderSubmitOutput.class); 
		if (salesOrderSubmitOutput == null) {
			logger.error("呼叫开放平台餐饮订单提交出错，外卖点餐失败。");
			res.setCode(1);
			res.setMessage("系统异常");
			return res;			
		} else if (SysConstants.OPEN_SUCCESS.equals(salesOrderSubmitOutput.getCode()) || "60032".equals(salesOrderSubmitOutput.getCode())) {
			Utils.removeSessionToken(httpRequest);
			CanyinSalesOrderSubmitOutput.Result result = salesOrderSubmitOutput.getResult();
			String orderId = result.getOrderId();
			if (!"-1".equals(status)) { // 堂食预下单不推送pos消息亦不推送管家号消息
				// 推送管家号下单模板消息
				wPosHttpClient.pushHouseKeeperOrderSubmitMsg(mid, orderId);
			}
			// 记录绑定信息			
			CateringSaleOrderBindingInput input = new CateringSaleOrderBindingInput();
			input.setMid(mid);
			input.setCardId(cardId);
			input.setSaleOrderId(orderId);
			CateringSaleOrderBindingOutput ouptut = (CateringSaleOrderBindingOutput) wizarposOpenRestClient.post(input, "/catering/saleorder/binding", CateringSaleOrderBindingOutput.class);			
			if (!StringUtils.isEmpty(tableId)) {// 正常提交，有餐桌号
				res.setCode(0);
				res.setObj(orderId);
				return res;	
			}
			res.setCode(-1);
			res.setObj(orderId);
			return res;
		} else {
			if ("60025".equals(salesOrderSubmitOutput.getCode())) {
				res.setCode(1);
				res.setMessage("桌子不可用，请找服务员点单");
				return res;					
			}
			if ("60035".equals(salesOrderSubmitOutput.getCode())) {
				res.setCode(1);
				res.setMessage("桌子已经开台，请在找服务员点单");
				return res;					
			}
			res.setCode(1);
			res.setMessage(salesOrderSubmitOutput.getMessage());
			return res;		
		}
	}	
	 
	/** 支付结果
	 * 
	 * @param mid
	 * @param orderId
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "/pay_ok")
	public ModelAndView payOk(
			@RequestParam(value = "orderId", required = true) String orderId,
			@RequestParam(value = "mid", required = true) String mid,
			HttpServletRequest httpRequest)
	{
		CateringSaleOrderQueryInput input = new CateringSaleOrderQueryInput();
		input.setMid(mid);
		input.setOrderId(orderId);
		CateringSaleOrderQueryOutput output = (CateringSaleOrderQueryOutput) wizarposOpenRestClient.post(input, "/catering/saleorder/query", CateringSaleOrderQueryOutput.class);		

		if (output == null || !SysConstants.OPEN_SUCCESS.equals(output.getCode())) {
			logger.error("餐饮订单查询失败，单号：" + orderId);
			if (output != null) {
				logger.error("餐饮订单查询失败：" + output.getMessage());
				if (SysConstants.NO_MERCHANT_CODE.equals(output.getCode())) {
					return new ModelAndView("error").addObject("err_message",
							SysConstants.NO_MERCHANT);
				}
			} else {
				return new ModelAndView("error").addObject("err_message",
						SysConstants.OPEN_ERROR_MESSAGE);
			}
		}
		SaleOrder result = output.getResult();
		if (result == null) {
			 return new ModelAndView("error").addObject("err_message",
						SysConstants.OPEN_ERROR_MESSAGE);
		}
		
		//餐饮类型(1堂吃2快餐3线下外卖4线上外卖)
 		switch (result.getOrderType()) {
			case "1": 
				result.setOrderType("堂食"); 
				break;
			case "2": 
				result.setOrderType("快餐"); 
				break;
			case "4": 
				result.setOrderType("外卖"); 
				break;
		}
 	
		return new ModelAndView("dgd_order/pay_ok").addObject("mid", mid)
				.addObject("orderId", orderId).addObject("order", result);
	}
	
	/**
	 * 进入呼叫
	 * 
	 * @param mid
	 * @param dateTime
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/tohujiao", method = RequestMethod.GET)
	@ResponseBody
	public ModelAndView toHujiao(
			@RequestParam(value = "mid", required = true) String mid,
			HttpServletRequest httpRequest) throws Exception
	{
		String openId = (String) httpRequest.getSession().getAttribute("openId");
		if (StringUtils.isEmpty(openId))
		{// session过期，跳转到登录注册页面
			return new ModelAndView("forward:/vip/login");
		}
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("mid", mid);
		// 请求微信 js api的完整页面地址
		String baseUrl = "http://"
				+ messageSource.getMessage(SysConstants.SERVICE_DNS, null,
						Locale.ENGLISH);
		baseUrl += httpRequest.getSession().getServletContext()
				.getContextPath();
		StringBuffer tmpUrl = new StringBuffer();
		tmpUrl.append(baseUrl);
		tmpUrl.append("/dgd/tohujiao");
		tmpUrl.append("?mid=").append(mid);
		String url = tmpUrl.toString();
		// 请求微信api的ticket
		AccessTokenInput jsInput = new AccessTokenInput();
		jsInput.setMid(mid);
		CommonResultOutput jsOutput = (CommonResultOutput) wizarposOpenRestClient
				.post(jsInput, "/weixin/ticket/js", CommonResultOutput.class);
		if (jsOutput == null
				|| SysConstants.OPEN_ERROR.equals(jsOutput.getCode()))
		{
			return new ModelAndView("error").addObject("err_message",
					SysConstants.OPEN_ERROR);
		} else if (SysConstants.NO_MERCHANT_CODE.equals(jsOutput.getCode()))
		{
			return new ModelAndView("error").addObject("err_message",
					SysConstants.NO_MERCHANT);
		} else
		{
			Map<String, String> result = (Map<String, String>) jsOutput
					.getResult();
			String jsTicket = result.get("ticket");
			String appid = result.get("appid");
			data.put("appId", appid);
			Map<String, String> ret = WxSignUtil.commonSign(jsTicket, url,
					WxSignUtil.createTimestamp());
			data.putAll(ret);
		}

		return new ModelAndView("dgd_order/hujiao", data);
	}

	/**
	 * 呼叫服务，通知商家，1呼叫加水，2呼叫买单，3提醒已经点单
	 * 
	 * @param table_id
	 * @param openId
	 * @param mid
	 * @param model
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "/callwaiter")
	public @ResponseBody String callWaiter(
			@RequestParam(value = "flag", required = true) String flag,
			@RequestParam(value = "tableId", required = true) String tableId,
			@RequestParam(value = "mid", required = true) String mid)
			throws UnsupportedEncodingException
	{
		String shopMid = null;
		// 请求开放平台获取桌号	
		GetTabelIdInput getTabelIdInput = new GetTabelIdInput();
		getTabelIdInput.setMid(mid);
		getTabelIdInput.setTicketId(MD5Util.MD5Encode(tableId, "UTF-8"));
		GetTabelIdOutput getTabelIdOutput = (GetTabelIdOutput) wizarposOpenRestClient.post(getTabelIdInput, "/dzx/getTabelId", GetTabelIdOutput.class);
		if (getTabelIdOutput == null) {
			logger.error("请求开放平台获取桌号失败");
			return "1";	
		} else if ("0".equals(getTabelIdOutput.getCode())) {
			GetTabelIdOutput.Result result = getTabelIdOutput.getResult();
			tableId = result.getTabelId();
			shopMid = result.getShopMid();
		} else { // 餐桌不存在
			return "3";	
		}
		// 校验餐桌是否是开桌状态
		Boolean isUsing = wPosHttpClient.isTableUsing(shopMid, tableId);
		if (!isUsing)
		{
			return "2";
		}

		// pos消息提醒推送
		StringBuffer msg = new StringBuffer();
		if ("1".equals(flag))
		{
			msg.append("需要加水");
		} else if ("2".equals(flag))
		{
			msg.append("需要买单");
		} else if ("3".equals(flag))
		{
			msg.append("已经点餐");
		}
		JSONObject param = new JSONObject();
		param.put("mid", shopMid);
		param.put("sendMessage", msg);
		param.put("tableId", tableId);
		try
		{
			wPosHttpClient.postOpen("/catering/service/call", param);
		} catch (Exception e)
		{
			// 消息推送失败
			logger.error("推送呼叫服务消息失败，餐桌ID = " + tableId);
			logger.error(e);
			return "1";
		}

		return "0";
	}
	

	/**
	 * 获取桌号
	 * 
	 * @param tableId
	 * @param mid
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "/getTableId")
	public @ResponseBody RespMessage callWaiter(
			@RequestParam(value = "tableId", required = true) String tableId,
			@RequestParam(value = "mid", required = true) String mid)
			throws UnsupportedEncodingException
	{
		RespMessage res = new RespMessage();
		String shopMid = null;
		// 请求开放平台获取桌号	
		GetTabelIdInput getTabelIdInput = new GetTabelIdInput();
		getTabelIdInput.setMid(mid);
		getTabelIdInput.setTicketId(MD5Util.MD5Encode(tableId, "UTF-8"));
		GetTabelIdOutput getTabelIdOutput = (GetTabelIdOutput) wizarposOpenRestClient.post(getTabelIdInput, "/dzx/getTabelId", GetTabelIdOutput.class);
		if (getTabelIdOutput == null) {
			logger.error("请求开放平台获取桌号失败");
			res.setCode(1);
			res.setMessage("系统异常，获取桌号失败");
			return res;	
		} else if ("0".equals(getTabelIdOutput.getCode())) {
			GetTabelIdOutput.Result result = getTabelIdOutput.getResult();
			Map<String, Object> data = new HashMap<String, Object>();
			tableId = result.getTabelId();
			shopMid = result.getShopMid();
			data.put("tableId", tableId);
			data.put("shopMid", shopMid);
			res.setObj(data);
			return res;
		} else { // 餐桌不存在
			res.setCode(3);
			res.setMessage("餐桌不存在");
			return res;	
		}
	}
}
